﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using S9Engine;
using System.Net.Mail;
using System.Text;

public partial class Ajax : Parser
{
    private bool _response;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            _parser.SetCurrentDir("~/tpl");

            _quantity = 1;
            _price = 0;

            if (string.IsNullOrEmpty(Session["Language"] as string)) Session["Language"] = _parser.GetConfig("DefaultLanguage", "VN");
            _currentLanguage = Session["Language"].ToString();

            _id = 0;
            _response = true;            

            if (!string.IsNullOrEmpty(Request["id"])) _id = long.Parse(Request["id"]);

            _parser.LoadContent("[%^Main%]{{errorCode}}[%$Main%]");

            switch (Request["type"])
            {
                case "contact": Contact(); break;
                case "language": ChangeLanguage(); break;
                //case "sendnews": SendNews(); break;
                //case "addtocart": AddToCart(); break;
                //case "updatecart": UpdateCart(); break;
                //case "deletecart": DeleteCart(); break;
                //case "clearcart": ClearCart(); break;
                //case "register": Register(); break;
                //case "login": Login(); break;
                //case "logout": Logout(); break;
                //case "update": Update(); break;
                //case "forgotpassword": ForgotPassword(); break;
                //case "resetpassword": ResetPassword(); break;
                //case "registerSale": RegisSale(); break;
                //case "sendorder": SendOrder(); break;
                //case "buyproduct": CheckLogin(); break;
                //case "updatenews": GetUpdateNews("update_news.html"); break;
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
        finally
        {
            if (_response)
            {
                _parser.Parse("Main");
                _parser.Out("Main");
            }
        }
    }

    private void ChangeLanguage()
    {
        string code = GetRequest("code");

        if (string.IsNullOrEmpty(code)) throw new Exception("Invalid language code!");

        Session["Language"] = code;

        AjaxResponse("OK: Change language done!");
    }

    private void SendNews()
    {
        string content = GetRequest("note");
        string email_send = GetRequest("email_send");
        string email = GetRequest("email");
        string newscid = GetRequest("newsCID");
        string newsid = GetRequest("newsID");
        string siteURL = _parser.GetConfig("siteURL", "viru.com.vn/tb");
        string link = "<a href='" + siteURL + "/News.aspx?cid=" + newscid + "&nid=" + newsid + "'>" + siteURL + "/News.aspx?cid=" + newscid + "&nid=" + newsid + "</a>";

        if (IsNullValues(email_send, email, content)) throw new Exception("Error: Invalid contact data!");

        string toEmail = _parser.GetConfig("CustomerEmail", "gnat0309@gmail.com");
        string subject1 = _parser.GetConfig("SendNews", "Viru") + " " + DateTime.Now.ToShortDateString();        

        string body1 = string.Format("<html><body><p>Chào bạn! Bạn đã nhận được tin tức từ viru.com.vn từ địa chỉ email: {0}</p><p>Hãy click vào đường link để xem chi tiết: {1}</p><p>{2}</p></body></html>", email_send, link, content);
        

        //Send mail qua mail trung gian        
        SendEmail(toEmail, "145313211", "Viru", email, email, subject1, body1);

        AjaxResponse("OK: Send email done!");
    }
    private void Contact()
    {
        string company = GetRequest("ctCompany");
        string fullName = GetRequest("ctName");
        string telephone = GetRequest("ctTelephone");
        string mobile = GetRequest("ctMobile");
        string address = GetRequest("ctAddress");
        string contact = GetRequest("ctContent");
        string email = GetRequest("ctEmail");

        if (IsNullValues(fullName, email, address, contact)) throw new Exception("Error: Invalid contact data!");

        string fromEmail = _parser.GetConfig("ContactSend", "thanhdattk4@gmail.com");
        string toEmail = _parser.GetConfig("ContactReceived", "nktang.a4@gmail.com");

        string subject1 = _parser.GetConfig("ContactSubject", "Viru") + " " + DateTime.Now.ToShortDateString();
        string subject2 = _parser.GetConfig("ContactSubjectCustomer", "Viru");

        string body1 = string.Format("<html><body><p>Thông tin liên hệ từ website</p><p /><p>Công ty: {0}</p><p>Họ và tên: {1}</p><p>Địa chỉ: {2}</p><p>Số điện thoại: {3}</p><p>Di động: {4}</p><p>Email: {5}</p><p>Nội dung: </p>{6}</p></body></html>", company, fullName, address, telephone, mobile, email, contact);
        string body2 = _parser.GetConfig("ContactContentCustomer", string.Empty);

        SendEmail(fromEmail, "145313211", fullName, toEmail, "Viru", subject1, body1);
        SendEmail(fromEmail, "145313211", "Viru", email, fullName, subject2, body2);

        AjaxResponse("OK: Send email done!");
    }

    private void AddToCart()
    {
        try
        {
            if (_id == 0) throw new Exception("Error: Invalid product ID");

            string quantityString = GetRequest("quantity");

            if (IsNullValues(quantityString)) throw new Exception("Error: Invalid product data");

            int quantity = 0;

            if (!int.TryParse(quantityString, out quantity)) throw new Exception("Error: Invalid product data");

            if (Session["AddToCart"] == null) Session["AddToCart"] = new List<MyCart>();

            List<MyCart> carts = Session["AddToCart"] as List<MyCart>;

            MyCart cart = null;

            if (carts != null) cart = carts.Where(c => c.ID.Equals(_id)).FirstOrDefault();

            if (cart == null)
            {
                var product = (from p in _DR.Products.Where(p => p.ID.Equals(_id))
                               join m in _DR.Meta.Where(m => m.Type == "product" && m.Key == "SalePrice") on p.ID equals m.Object into mtfun
                               from mt in mtfun.DefaultIfEmpty()
                               select new
                               {
                                   ID = p.ID,
                                   Name = p.Name,
                                   Description = p.Description,
                                   Price = p.Price,
                                   SalePrice= mt.Value,
                                   Image = p.Image
                               }).FirstOrDefault();

                string realPrice = (product.SalePrice != "0" && double.Parse(product.SalePrice) < product.Price) ? product.SalePrice : product.Price.ToString();
                carts.Add(new MyCart() { ID = _id, Name = product.Name ?? string.Empty, Quantity = quantity, Price = double.Parse(realPrice)});
            }
            else
            {
                cart.Quantity += quantity;
            }

            string totalQuantity = carts.Sum(c => c.Quantity).ToString();
            string totalPrice = carts.Sum(c => c.Quantity * c.Price).ToString("N0").Replace(',','.');

            AjaxResponse(totalQuantity + "@" + totalPrice);

            carts = null;
            cart = null;
        }
        catch (Exception ex)
        {
            _parser.Assign("errorCode", ex.ToString());
        }
    }

    private void UpdateCart()
    {
        int[] Quantity = GetRequest("pCartQuantity").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();
        long[] IDs = GetRequest("productID").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(p => long.Parse(p)).ToArray();

        if (Quantity.Count() == 0 || IDs.Count() == 0) throw new Exception("Error");

        if (Session["AddToCart"] == null) Session["AddToCart"] = new List<MyCart>();

        List<MyCart> carts = Session["AddToCart"] as List<MyCart>;

        for (int i = 0; i < Quantity.Count(); i++)
        {
            if (Quantity[i] == 0) { carts.RemoveAt(i); }
            else
            {
                carts.Where(c => c.ID.Equals(IDs[i])).FirstOrDefault().Quantity = Quantity[i];
            }
        }

        AjaxResponse("OK: Update cart done!");        
    }

    private void DeleteCart()
    {
        if (_id == 0) throw new Exception("Error: Invalid product ID");

        if (Session["AddToCart"] == null) throw new Exception("Empty cart");

        List<MyCart> carts = Session["AddToCart"] as List<MyCart>;

        carts.Remove(carts.FirstOrDefault(c => c.ID.Equals(_id)));

        AjaxResponse("OK: Delete cart done!");
    }

    private void ClearCart()
    {
        Session["AddToCart"] = null;
        AjaxResponse("OK: Clear cart done!");
    }

    private void Register()
    {
        //_DR.Refresh(System.Data.Objects.RefreshMode.StoreWins, _DR.Users);

        string fullname = GetRequest("fullname");        
        string address = GetRequest("address");
        string phone = GetRequest("phone");
        string email = GetRequest("email");
        string password = GetRequest("password");
        string month = GetRequest("month");
        string day = GetRequest("day");
        string year = GetRequest("year");        

        if (IsNullValues(fullname, address, phone, email, password, month, day, year)) throw new Exception("Error: Invalid user data!");

        if (_DR.Users.Where(u => u.Username.Equals(email)).Count() > 0) throw new Exception("ErrorCode=1");

        Users user = new Users();

        user.Fullname = fullname;
        user.LanguageCode = _currentLanguage;
        user.Username = email;
        user.Type = "Customer";
        user.Password = _parser.MD5Enc(password);
        user.LanguageCode = _currentLanguage;
        
        _DR.AddToUsers(user);
        _DR.SaveChanges();

        AddNewMeta(user.ID, "Customer", "FullName", fullname, false);        
        AddNewMeta(user.ID, "Customer", "Address", address, false);
        AddNewMeta(user.ID, "Customer", "Phone", phone, false);
        AddNewMeta(user.ID, "Customer", "Email", email, false);
        AddNewMeta(user.ID, "Customer", "Month", month, false);
        AddNewMeta(user.ID, "Customer", "Day", day, false);
        AddNewMeta(user.ID, "Customer", "Year", year, false);        

        _DR.SaveChanges();

        ////Send email register success (local error find path file)
        //string body = System.IO.File.ReadAllText(Server.MapPath("webcms/uploads/mail/RegisterSuccess.txt"));
        //string bodydecode = HttpUtility.HtmlDecode(body);
        ////string body = "Đăng ký thành công";

        //string fromEmail = _parser.GetConfig("ContactEmail", "netpro.hn.vn@gmail.com");
        //string subject1 = _parser.GetConfig("ContactSubject", "NetPro") + " " + DateTime.Now.ToShortDateString();
        //string subject2 = _parser.GetConfig("ContactSubjectCustomer", "NetPro");

        //SendEmail(fromEmail, "145313211", "E-Commerce", fromEmail, "E-Commerce", subject1, bodydecode);
        SendEmail("gnat0309@gmail.com", "145313211", "Hiền lương - Siêu thị nội thất", email, "Hiền lương - Siêu thị nội thất", "Bạn chưa đăng ký", "Bạn đã đăng ký thành công!");

        Session["Logged"] = true;
        Session["Fullname"] = user.Fullname;
        Session["UserEmail"] = user.Username;

        AjaxResponse("OK: Register done!");
    }

    private void Login()
    {
        string username = GetRequest("username");
        string password = _parser.MD5Enc(GetRequest("password"));
        string cookie = GetRequest("cookie");

        if (IsNullValues(username, password)) throw new Exception("Invalid login data!");

        Users user = _DR.Users.Where(u => u.Username.Equals(username) && u.Type.Equals("Customer") && u.Password.Equals(password)).FirstOrDefault();

        if (null == user)
        {
            Session["Logged"] = null;
            Session["Fullname"] = null;
            Session["UserEmail"] = null;
            Session["UserID"] = null;

            throw new Exception("Login failed!");
        }
        else
        {
            Session["Logged"] = true;
            Session["Fullname"] = user.Fullname;
            Session["UserEmail"] = user.Username;
            Session["UserID"] = user.ID.ToString();            

            if (cookie == "on")
            {
                CreateCookie("AutoLogin", "True");
                CreateCookie("Username", username);
                CreateCookie("Password", password);
            }
            else
            {
                DeleteCookie("AutoLogin");
                DeleteCookie("Username");
                DeleteCookie("Password");
            }

            AjaxResponse("OK: Login done!");
        }

        AjaxResponse("OK: Login done!");
    }

    private void Logout()
    {
        Session["Logged"] = null;
        Session["Fullname"] = null;
        Session["UserEmail"] = null;
        DeleteCookie("AutoLogin");

        AjaxResponse("OK: Logout done!");
    }

    private void Update()
    {
        _DR.Refresh(System.Data.Objects.RefreshMode.StoreWins, _DR.Users);

        string fullname = GetRequest("fullname");        
        string address = GetRequest("address");
        string phone = GetRequest("phone");
        string email = GetRequest("email");
        string currentPassword = _parser.MD5Enc(GetRequest("currentPassword"));
        string password = GetRequest("password");
        string month = GetRequest("month");
        string day = GetRequest("day");
        string year = GetRequest("year");        

        if (IsNullValues(fullname, address, phone, email, currentPassword, password, month, day, year)) throw new Exception("Error: Invalid user data!");

        Users user = _DR.Users.FirstOrDefault(u => u.Username.Equals(email) && u.Password.Equals(currentPassword));

        if (null == user) throw new Exception("Invalid user data!");

        user.Fullname = fullname;
        user.Username = email;
        user.Password = _parser.MD5Enc(password);
        user.LanguageCode = _currentLanguage;

        EditMetaByObject(user.ID, "Customer", "FullName", fullname, false);        
        EditMetaByObject(user.ID, "Customer", "Address", address, false);
        EditMetaByObject(user.ID, "Customer", "Phone", phone, false);
        EditMetaByObject(user.ID, "Customer", "Email", email, false);
        EditMetaByObject(user.ID, "Customer", "Month", month, false);
        EditMetaByObject(user.ID, "Customer", "Day", day, false);
        EditMetaByObject(user.ID, "Customer", "Year", year, false);        

        Session["Fullname"] = user.Fullname;
        Session["UserEmail"] = user.Username;

        _DR.SaveChanges();

        AjaxResponse("OK: Update account done!");
    }

    private void ForgotPassword()
    {
        string email = GetRequest("currentEmail");

        if (IsNullValues(email)) throw new Exception("Invalid email");

        Users user = _DR.Users.Where(u => u.Username.Equals(email)).FirstOrDefault();

        if (null == user) throw new Exception("Invalid email");

        string fromEmail = _parser.GetConfig("ContactEmail", "noreply@dinorich.com");

        LoadFile("sendpassword.html", true);

        _parser.Assign("userFullname", user.Fullname);
        _parser.Assign("passwordKey", user.Password);
        _parser.Assign("userEmail", user.Username);

        _parser.Parse("Main");
        _parser.Out("Main");

        string subject = "Mật khẩu user tại Hiền Lương";

        SendEmail(fromEmail, "145313211", "Hiền Lương - Siêu thị nội thất", email, user.Fullname, subject, _parser._outContent);

        _parser.LoadContent("[%^Main%]{{errorCode}}[%$Main%]");

        AjaxResponse("OK: Send password done!");
    }

    private void ResetPassword()
    {
        string password = GetRequest("password");
        string email = GetRequest("email");
        string currentPassword = GetRequest("key");

        Users user = _DR.Users.FirstOrDefault(u => u.Username.Equals(email) && u.Password.Equals(currentPassword));

        if (null == user) throw new Exception("Invalid user email or key!");

        user.Password = _parser.MD5Enc(password);

        _DR.SaveChanges();

        AjaxResponse("OK: Reset password done!");
    }
    private void RegisSale(){
        string email = GetRequest("txtEmail");
        if (IsNullValues(email)) throw new Exception("Error: Invalid user data!");

        if (_DR.Meta.Where(m => m.Type.Equals("RegisSale") && m.Value.Equals(email)).ToList().Count == 0)
        {
            AddNewMeta(100, "RegisSale", email, email, true);
            AjaxResponse("OK: Register done!");
        }     
    }

    private void SendOrder()
    {
        string company = GetRequest("shippingCompany");
        string address = GetRequest("shippingAddress");
        string telephone = GetRequest("shippingPhone");
        string mobile = GetRequest("shippingMobile");
        string email = GetRequest("shippingEmail");
        string note = GetRequest("shippingContent");

        if (IsNullValues(address, email, note) || Session["AddToCart"] == null) { throw new Exception("Error: Invalid contact data!"); return; }

        string subject1 = _parser.GetConfig("ContactSubject", "Viru") + " " + DateTime.Now.ToShortDateString();
        string subject2 = _parser.GetConfig("ContactSubjectCustomer", "Viru");
        string body2 = _parser.GetConfig("ContactOrderCustomer", "Xin cảm ơn quý khách đã mua hàng, chúng tôi sẽ liên lạc lại trong thời gian ngắn nhất.");
        string siteName = _parser.GetConfig("SiteName", "viru.com.vn");
        string fromEmail = _parser.GetConfig("ContactSend", "gnat0309@gmail.com");

        List<MyCart> carts = Session["AddToCart"] as List<MyCart>;
        var products = (from c in carts
                        join p in _DR.Products
                        on c.ID equals p.ID
                        select new
                        {
                            ID = p.ID,
                            Name = p.Name,
                            Quantity = c.Quantity,
                            Image = p.Image,
                            Price = p.Price
                        }).ToList();

        if (products.Count == 0) return;

        long orderID = AddNewOrder(company, email, telephone, products.Sum(p => p.Quantity), 0, true);

        int i = 0;
        StringBuilder sb = new StringBuilder();

        sb.Append("<html><body>");
        sb.Append("<p>Dear " + company + "! </p>");
        sb.Append("<p>Địa chỉ: " + address + " </p>");
        sb.Append("<p>Điện thoại NR/ công ty: <b>" + telephone + "</b> </p>");
        sb.Append("<p>Điện thoại di động: <b>" + mobile + "</b> </p>");
        sb.Append("<p style='font-style: italic;'>Email: " + email + "</p>");
        sb.Append("<p style='border-botom: 1px solid #a4a4a4a'>Nội dung: " + note + " </p>");
        sb.Append("<p style='border-botom: 1px solid #a4a4a4a'>Bạn đã đặt mua đơn hàng dưới tại " + siteName + ". Chúng tôi sẽ sớm liên hệ với bạn.<br/>Xin chân thành cảm ơn!</p>");

        sb.Append("<table cellspacing='0' cellpadding='0' id='cartTable' style='border-collapse:collapse;'>");
        sb.Append("<thead style='background: #D90000; font-weight:bold; text-align:center;'>");
        sb.Append("<tr>");
        sb.Append("<th width='2%' style='white-space:nowrap;border:1px solid #CCCCCC;padding:5px;'>Thứ tự</th><th width='2%' style='white-space:nowrap;border:1px solid #CCCCCC;padding:5px;'>Ảnh</th><th width='44%' style='white-space:nowrap;border:1px solid #CCCCCC;padding:5px;'>Tên sản phẩm</th><th width='20%'style='white-space:nowrap;border:1px solid #CCCCCC;padding:5px;'>Giá tiền</th><th width='5%'style='white-space:nowrap;border:1px solid #CCCCCC;padding:5px;'>Số lượng</th><th width='25%'style='white-space:nowrap;border:1px solid #CCCCCC;padding:5px;'>Tổng tiền</th>");
        sb.Append("</tr>");
        sb.Append("</thead>");
        sb.Append("<tbody>");

        string siteURL = _parser.GetConfig("siteURL", "http://www.viru.com.vn/webcms");
        double priceSum = 0;
        List<Meta> metas = _DR.Meta.Where(m => m.Type.Equals("product") && m.Key.Equals("SalePrice")).ToList();
        foreach (var p in products)
        {
            ++i;
            double tmpPrice = long.Parse(metas.Where(m => m.Object.Equals(p.ID)).Select(m => m.Value.Replace(",", "")).FirstOrDefault());
            double price = (tmpPrice != 0) ? tmpPrice : p.Price;
            double productsPrice = p.Quantity * price;
            priceSum += productsPrice;
            sb.Append("<tr>");
            sb.Append("<td style='color:#FF8C1A;font-weight:bold;white-space:nowrap;border:1px solid #CCCCCC;padding:5px;'>" + i.ToString() + "</td>");
            sb.Append("<td style='text-align:center !important;white-space:nowrap;border:1px solid #CCCCCC;padding:5px;' img alt='Viru' src='>" + siteURL + p.Image.ToString() + "' /></td>");
            sb.Append("<td style='text-align:left !important;white-space:nowrap;border:1px solid #CCCCCC;padding:5px;'><a href='#'>" + p.Name + "</a></td>");
            sb.Append("<td style='color:#dd0000;white-space:nowrap;border:1px solid #CCCCCC;padding:5px;'>" + price.ToString("N0").Replace(",", ".") + " ₫</td>");
            sb.Append("<td style='text-align:center !important;white-space:nowrap;border:1px solid #CCCCCC;padding:5px;'>" + p.Quantity + "</td>");
            sb.Append("<td style='color:#dd0000;white-space:nowrap;border:1px solid #CCCCCC;padding:5px;'>" + productsPrice.ToString("N0").Replace(",", ".") + " ₫</td>");
            sb.Append("</tr>");
            AddNewRelations(p.ID, orderID, p.Quantity, "order-product", false);

            Meta mt = _DR.Meta.Where(m => m.Type.Equals("product") && m.Key.Equals("Buy") && m.Object.Equals(p.ID)).FirstOrDefault();
            if (null != mt) EditMetaByObject(p.ID, "product", "Buy", (int.Parse(mt.Value) + p.Quantity).ToString(), false);
            else { AddNewMeta(p.ID, "product", "Buy", p.Quantity.ToString(), false); }
        }
        AddNewMeta(orderID, "order", "Time", DateTime.Now.ToShortDateString(), false);
        AddNewMeta(orderID, "order", "Address", address, false);
        EditOrderByID(orderID, priceSum, true);

        sb.Append("<tfoot>");
        sb.Append("<tr>");
        sb.Append("<td colspan=3></td>");
        sb.Append("<td style='text-align:right;' colspan='3'>Thành tiền: <strong style='color:#dd0000;'>" + priceSum.ToString("N0").Replace(",", ".") + " ₫ </strong></td>");
        sb.Append("</tr>");
        sb.Append("</tfoot>");
        sb.Append("</tbody></body></html>");

        string body1 = string.Format(sb.ToString());

        //SendEmail(fromEmail, "145313211", "Hiền lương - Siêu thị nội thất", email, fullName, subject1, body2);
        SendEmail(fromEmail, "145313211", "Viru", email, company, subject1, body1);

        AjaxResponse("OK: Send email done!");
    }

    //private void SendOrder()
    //{
    //    string fullName = GetRequest("shippingName");
    //    string address = GetRequest("shippingAddress");
    //    string telephone = GetRequest("shippingPhone");
    //    string email = GetRequest("shippingEmail");
    //    string note = GetRequest("shippingContact");

    //    if (IsNullValues(fullName, telephone, email) || Session["AddToCart"] == null) throw new Exception("Error: Invalid contact data!");


    //    string subject1 = _parser.GetConfig("ContactSubject", "Viru") + " " + DateTime.Now.ToShortDateString();
    //    string subject2 = _parser.GetConfig("ContactSubjectCustomer", "Viru");
    //    string body2 = _parser.GetConfig("ContactOrderCustomer", "Xin cảm ơn quý khách đã mua hàng, chúng tôi sẽ liên lạc lại trong thời gian ngắn nhất.");
    //    string siteName = _parser.GetConfig("SiteName", "viru.com");
    //    string fromEmail = _parser.GetConfig("ContactEmail", "gnat0309@gmail.com");

    //    List<MyCart> carts = Session["AddToCart"] as List<MyCart>;
    //    var products = (from c in carts
    //                    join p in _DR.Products
    //                    on c.ID equals p.ID
    //                    select new
    //                    {
    //                        ID = p.ID,
    //                        Name = p.Name,
    //                        Quantity = c.Quantity,
    //                        Image = p.Image,
    //                        Price = p.Price
    //                    }).ToList();

    //    if (products.Count == 0) return;

    //    long orderID = AddNewOrder(fullName, email, telephone, products.Sum(p => p.Quantity), 0, true);

    //    int i = 0;
    //    StringBuilder sb = new StringBuilder();

    //    sb.Append("<html><body>");
    //    sb.Append("<p>Dear " + fullName + "! </p>");
    //    sb.Append("<p>Địa chỉ: " + address + " </p>");
    //    sb.Append("<p>Số điện thoại: <b>" + telephone + "</b> </p>");
    //    sb.Append("<p style='font-style: italic;'>Email: " + email + "</p>");
    //    sb.Append("<p style='border-botom: 1px solid #a4a4a4a'>Nội dung: " + note + " </p>");
    //    sb.Append("<p style='border-botom: 1px solid #a4a4a4a'>Bạn đã đặt mua đơn hàng dưới tại " + siteName + ". Chúng tôi sẽ sớm liên hệ với bạn.<br/>Xin chân thành cảm ơn!</p>");

    //    sb.Append("<table cellspacing='0' cellpadding='0' id='cartTable' style='border-collapse:collapse;'>");
    //    sb.Append("<thead style='background:#f2f2f2; font-weight:bold; text-align:center;'>");
    //    sb.Append("<tr>");
    //    sb.Append("<th width='2%' style='white-space:nowrap;border:1px solid #e1e1e1;padding:5px;'>Thứ tự</th><th width='2%' style='white-space:nowrap;border:1px solid #e1e1e1;padding:5px;'>Ảnh</th><th width='44%' style='white-space:nowrap;border:1px solid #e1e1e1;padding:5px;'>Tên sản phẩm</th><th width='20%'style='white-space:nowrap;border:1px solid #e1e1e1;padding:5px;'>Giá tiền</th><th width='5%'style='white-space:nowrap;border:1px solid #e1e1e1;padding:5px;'>Số lượng</th><th width='25%'style='white-space:nowrap;border:1px solid #e1e1e1;padding:5px;'>Tổng tiền</th>");
    //    sb.Append("</tr>");
    //    sb.Append("</thead>");
    //    sb.Append("<tbody>");

    //    double priceSum = 0;
    //    List<Meta> metas = _DR.Meta.Where(m => m.Type.Equals("product") && m.Key.Equals("SalePrice")).ToList();
    //    foreach (var p in products)
    //    {
    //        ++i;
    //        double tmpPrice = long.Parse(metas.Where(m => m.Object.Equals(p.ID)).Select(m => m.Value.Replace(",", "")).FirstOrDefault());
    //        double price = (tmpPrice != 0) ? tmpPrice : p.Price;
    //        double productsPrice = p.Quantity * price;
    //        priceSum += productsPrice;
    //        sb.Append("<tr>");
    //        sb.Append("<td style='color:#FF8C1A;font-weight:bold;white-space:nowrap;border:1px solid #e1e1e1;padding:5px;'>" + i.ToString() + "</td>");
    //        sb.Append("<td style='text-align:center !important;white-space:nowrap;border:1px solid #e1e1e1;padding:5px;' img alt='HaiNam' src='>" + _webcmsPath + p.Image.ToString() + "' /></td>");
    //        sb.Append("<td style='text-align:left !important;white-space:nowrap;border:1px solid #e1e1e1;padding:5px;'><a href='#'>" + p.Name + "</a></td>");
    //        sb.Append("<td style='color:#dd0000;white-space:nowrap;border:1px solid #e1e1e1;padding:5px;'>" + price.ToString("N0").Replace(",", ".") + " ₫</td>");
    //        sb.Append("<td style='text-align:center !important;white-space:nowrap;border:1px solid #e1e1e1;padding:5px;'>" + p.Quantity + "</td>");
    //        sb.Append("<td style='color:#dd0000;white-space:nowrap;border:1px solid #e1e1e1;padding:5px;'>" + productsPrice.ToString("N0").Replace(",", ".") + " ₫</td>");
    //        sb.Append("</tr>");
    //        AddNewRelations(p.ID, orderID, p.Quantity, "order-product", false);

    //        Meta mt = _DR.Meta.Where(m => m.Type.Equals("product") && m.Key.Equals("Buy") && m.Object.Equals(p.ID)).FirstOrDefault();
    //        if (null != mt) EditMetaByObject(p.ID, "product", "Buy", (int.Parse(mt.Value) + p.Quantity).ToString(), false);
    //        else { AddNewMeta(p.ID, "product", "Buy", p.Quantity.ToString(), false); }
    //    }
    //    AddNewMeta(orderID, "order", "Time", DateTime.Now.ToShortDateString(), false);
    //    AddNewMeta(orderID, "order", "Address", address, false);
    //    EditOrderByID(orderID, priceSum, true);

    //    sb.Append("<tfoot>");
    //    sb.Append("<tr>");
    //    sb.Append("<td colspan=3></td>");
    //    sb.Append("<td style='text-align:right;' colspan='3'>Thành tiền: <strong style='color:#dd0000;'>" + priceSum.ToString("N0").Replace(",", ".") + " ₫ </strong></td>");
    //    sb.Append("</tr>");
    //    sb.Append("</tfoot>");
    //    sb.Append("</tbody></body></html>");

    //    string body1 = string.Format(sb.ToString());

    //    //SendEmail(fromEmail, "145313211", "Hiền lương - Siêu thị nội thất", email, fullName, subject1, body2);
    //    SendEmail(fromEmail, "145313211", "Hiền lương - Siêu thị nội thất", email, fullName, subject1, body1);

    //    AjaxResponse("OK: Send email done!");
    //}

    private void GetUpdateNews(string htmlFile)
    {
        try
        {
            LoadFile(htmlFile, true);
            int page = int.Parse(Request["page"]);

            List<NewsList> news = new List<NewsList>();
            news = (from post in _DR.Posts.Where(p => p.LanguageCode.Equals(_currentLanguage))
                    //join metaNews in _DR.Meta.Where(m => m.Type.Equals("news") && m.Key.Equals("NewsHot") && (!isHot || m.Value.Equals("on"))) on post.ID equals metaNews.Object
                    join metaImage in _DR.Meta.Where(m => m.Type.Equals("news") && m.Key.Equals("NewsImage")) on post.ID equals metaImage.Object into metaImageFun
                    from mimg in metaImageFun.DefaultIfEmpty()
                    join relation1 in _DR.Relations.Where(r => r.Type.Equals("news-category")) on post.ID equals relation1.Child
                    join term in _DR.Terms on relation1.Parent equals term.ID
                    orderby post.ID descending
                    select new NewsList()
                    {
                        ID = post.ID,
                        Title = post.Title,
                        Excerpt = post.Excerpt,
                        Date = post.Date,
                        Image = mimg.Value,
                        CategoryID = term.ID,
                        CategoryName = term.Name
                    }).OrderByDescending(p => p.Date).ThenByDescending(p => p.ID).ToList();

            if (null == news) { _parser.Parse(string.Format("{0}.Noresult", "Main")); return; }
            ParseNewsListWithPaging(news, "UpdateNews", "", "");
        }
        catch (Exception ex)
        {
            _parser.Assign("errorCode", ex.ToString() + " " + Request["page"]);
        }
    }

    
    private void CheckLogin() {
        if ((bool)Session["Logged"] != true) throw new Exception("Error not Login");
        else{
            AjaxResponse("OK: Login!");
        }
    }

    private void AjaxResponse(string value)
    {
        _parser.Assign("errorCode", value);
    }

    private void SendEmail(string fromEmail, string fromPassword, string fromName, string toEmail, string toName, string subject, string body)
    {
        var fromAddress = new MailAddress(fromEmail, fromName);
        var toAddress = new MailAddress(toEmail, toName);

        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new System.Net.NetworkCredential(fromAddress.Address, fromPassword)
        };

        using (var message = new MailMessage(fromAddress, toAddress)
        {
            BodyEncoding = System.Text.Encoding.UTF8,
            IsBodyHtml = true,
            SubjectEncoding = System.Text.Encoding.UTF8,
            Subject = subject,
            Body = body
        })
        {
            smtp.Send(message);
        };

        smtp = null;
    }
}